/*
    DIMVisual-KAAPI, the DIMVisual bundle for KAAPI trace files
    Copyright (c) 2008 Lucas Mello Schnorr <schnorr@gmail.com>

    This file is part of DIMVisual-KAAPI.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "KAAPIRecordReaderObjc.h"

@implementation KAAPIRecordReaderObjc


- (id) initWithFile: (const std::string&) filename;
{
	self = [super init];

	_start = (Util::ka_uint8_t*)-1;
	_size = 0;

	/* use mmap version */
	int fd = open( filename.c_str(), O_RDWR, S_IRUSR|S_IWUSR|S_IRGRP );
	if (fd == -1){
		[super release];
		return nil;
	}
	struct stat st;
	int err = fstat( fd, &st );
	if (err !=0){
		[super release];
		return nil;
	}
	
	_size = st.st_size;
//	std::cout << "Size file:" << _size << std::endl;
	void* start = mmap( 0, _size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
	if (start == (void*)-1) {
		close( fd );
		[super release];
		return nil;
	}
//	fprintf (stderr, "start = %p\n", start);
	_start = (Util::ka_uint8_t*)start;
        ipos = _start;
        iend = _start + _size;
	close( fd );
	return self;
}

- (Util::Record*) read
{
	if (ipos < iend) {
		Util::Record* r = (Util::Record*)ipos;
		ipos += r->_size;
		return r;
	}
	return NULL;
}
@end
